<template>
	<view class="reservation-list-container">

		<view class="search-filter-section">
			<view class="search-box">
				<uni-icons type="search" size="20" color="#999"></uni-icons>
				<input 
					type="text" 
					v-model="searchKeyword" 
					placeholder="搜索预约记录" 
					@confirm="handleSearch"
				/>
				<view class="clear-icon" v-if="searchKeyword" @click="clearSearch">
					<uni-icons type="clear" size="20" color="#999"></uni-icons>
				</view>
			</view>
			
			<view class="filter-box">
				<view class="filter-scrollview">
					<picker 
						mode="selector" 
						:range="statusOptions" 
						range-key="label"
						:value="statusFilterIndex" 
						@change="onStatusFilterChange"
					>
						<view class="filter-item" :class="{'active': statusFilterIndex > 0}">
							<text>{{ statusOptions[statusFilterIndex].label }}</text>
							<view class="arrow-icon">
								<uni-icons type="bottom" size="12" color="#666"></uni-icons>
							</view>
						</view>
					</picker>
					
					<picker 
						mode="date" 
						:value="dateFilter" 
						@change="onDateFilterChange"
					>
						<view class="filter-item" :class="{'active': dateFilter}">
							<text>{{ dateFilter || '选择日期' }}</text>
							<view class="arrow-icon">
								<uni-icons type="bottom" size="12" color="#666"></uni-icons>
							</view>
						</view>
					</picker>
				</view>
				
				<view class="reset-filter" @click="clearFilters" v-if="hasFilters">
					<uni-icons type="reload" size="14" color="#4a6bdf"></uni-icons>
					<text>重置</text>
				</view>
			</view>
		</view>
		
		<view class="content-section">
			<view v-if="loading" class="loading-box">
				<uni-load-more status="loading" />
			</view>
			
			<view v-else-if="reservations.length === 0" class="empty-box">
				<image src="/static/empty.png" mode="aspectFit" class="empty-icon"></image>
				<text class="empty-text">暂无预约记录</text>
				<text class="empty-sub-text">您还没有任何预约记录</text>
			</view>
			
			<view v-else class="list-content">
				<view 
					v-for="(item, index) in reservations" 
					:key="index" 
					class="reservation-card"
				>
					<view class="card-header">
						<text class="exhibition-title">{{ item.exhibitionTitle || '博物馆参观' }}</text>
						<text :class="['status-tag', getStatusClass(item.status)]">{{ getStatusText(item.status) }}</text>
					</view>
					<view class="card-body">
						<view class="info-item">
							<view class="info-icon date-icon">
								<uni-icons type="calendar" size="16" color="#4a6bdf"></uni-icons>
							</view>
							<text class="info-text">{{ item.visitDate || formatDate(item.visitTime) }}</text>
						</view>
						<view class="info-item">
							<view class="info-icon time-icon">
								<uni-icons type="clock" size="16" color="#5ac8fa"></uni-icons>
							</view>
							<text class="info-text">{{ item.visitTimeSlot || formatTime(item.visitTime) }}</text>
						</view>
						<view class="info-item">
							<view class="info-icon person-icon">
								<uni-icons type="person" size="16" color="#ff9500"></uni-icons>
							</view>
							<text class="info-text">{{ item.visitorCount }}人</text>
						</view>
					</view>
					<view class="card-footer">
						<text class="create-time">预约时间：{{ formatDateTime(item.createTime) }}</text>
			
						<!-- 操作按钮区域 -->
						<view class="card-actions">
							<template v-if="item.status === 0 || item.status === 1">
								<button class="action-btn edit-btn" @click.stop="handleEdit(item)">
									<text>修改</text>
								</button>
								<button class="action-btn cancel-btn" @click.stop="handleCancel(item)">
									<text>取消预约</text>
								</button>
							</template>
							<template v-else-if="item.status === 2">
								<button class="action-btn delete-btn" @click.stop="handleDelete(item)">
									<text>删除</text>
								</button>
								<button class="action-btn review-btn" @click.stop="handleReview(item)">
									<text>评价</text>
								</button>
							</template>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { getMyReservations, cancelReservation, deleteReservation } from '@/api/reservation.js';
import { getImageUrl } from '@/api/file.js';

export default {
	setup() {
		const loading = ref(true);
		const reservations = ref([]);
		
		const searchKeyword = ref('');
		const statusFilterIndex = ref(0);
		const dateFilter = ref('');
		
		const statusOptions = [
			{ value: -1, label: '全部状态' },
			{ value: 0, label: '待审核' },
			{ value: 1, label: '待参观' },
			{ value: 2, label: '已失效' }
		];
		
		const hasFilters = computed(() => {
			return searchKeyword.value || statusFilterIndex.value > 0 || dateFilter.value;
		});
		
		// 日期格式化函数
		const formatDate = (dateString, fallback = '') => {
			if (!dateString) return fallback;
			
			try {
				const date = new Date(dateString);
				if (isNaN(date.getTime())) return fallback;
				
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			} catch (e) {
				return fallback;
			}
		};
		
		// 时间格式化函数
		const formatTime = (dateString, fallback = '') => {
			if (!dateString) return fallback;
			
			try {
				const date = new Date(dateString);
				if (isNaN(date.getTime())) return fallback;
				
				return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			} catch (e) {
				return fallback;
			}
		};
		
		// 日期时间格式化函数
		const formatDateTime = (dateString, fallback = '') => {
			if (!dateString) return fallback;
			
			try {
				const date = new Date(dateString);
				if (isNaN(date.getTime())) return fallback;
				
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			} catch (e) {
				return fallback;
			}
		};
		
		// 初始化
		onMounted(() => {
			loadReservations();
		});
		
		// 加载预约列表
		const loadReservations = async () => {
			loading.value = true;
			try {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo) {
					uni.navigateTo({ url: '/pages/login/index' });
					return;
				}
				
				const res = await getMyReservations(userInfo.id);
				if (res.code === 200) {
					// 先获取所有预约
					let filteredReservations = res.data;
					
					// 按关键字筛选
					if (searchKeyword.value) {
						filteredReservations = filteredReservations.filter(item => 
							(item.id && item.id.toString().includes(searchKeyword.value)) ||
							(item.visitDate && item.visitDate.includes(searchKeyword.value)) ||
							(item.visitTimeSlot && item.visitTimeSlot.includes(searchKeyword.value))
						);
					}
					
					// 按状态筛选
					if (statusFilterIndex.value > 0) {
						const statusValue = statusOptions[statusFilterIndex.value].value;
						filteredReservations = filteredReservations.filter(item => 
							item.status === statusValue
						);
					}
					
					// 按日期筛选
					if (dateFilter.value) {
						filteredReservations = filteredReservations.filter(item => 
							item.visitDate === dateFilter.value
						);
					}
					
					reservations.value = filteredReservations;
				} else {
					uni.showToast({
						title: res.message || '获取预约列表失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取预约列表出错:', error);
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			} finally {
				loading.value = false;
			}
		};
		
		// 格式化身份证显示
		const formatIdCard = (idCard) => {
			if (!idCard) return '无';
			return idCard.substring(0, 6) + '********' + idCard.substring(14);
		};
		
		// 获取状态文本
		const getStatusText = (status) => {
			const statusMap = {
				0: '待审核',
				1: '待参观',
				2: '已失效'
			};
			return statusMap[status] || '未知状态';
		};
		
		// 获取状态类
		const getStatusClass = (status) => {
			const statusClassMap = {
				0: 'status-pending',
				1: 'status-upcoming',
				2: 'status-expired'
			};
			return statusClassMap[status] || '';
		};
		
		// 处理搜索
		const handleSearch = () => {
			loadReservations();
		};
		
		// 清除搜索关键字
		const clearSearch = () => {
			searchKeyword.value = '';
			loadReservations();
		};
		
		// 状态筛选变更
		const onStatusFilterChange = (e) => {
			statusFilterIndex.value = e.detail.value;
			loadReservations();
		};
		
		// 日期筛选变更
		const onDateFilterChange = (e) => {
			dateFilter.value = e.detail.value;
			loadReservations();
		};
		
		// 清除所有筛选条件
		const clearFilters = () => {
			searchKeyword.value = '';
			statusFilterIndex.value = 0;
			dateFilter.value = '';
			loadReservations();
		};
		
		// 处理修改预约
		const handleEdit = (item) => {
			uni.navigateTo({
				url: `/pages/reservation/edit?id=${item.id}`
			});
		};
		
		// 处理取消预约
		const handleCancel = (item) => {
			// 检查预约状态是否为待审核或已确认(状态0或1)
			if (item.status !== 0 && item.status !== 1) {
				uni.showToast({
					title: '该预约无法取消',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			uni.showModal({
				title: '取消预约',
				content: '确定要取消此预约吗？取消后将无法恢复。',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '取消中...' });
						try {
							const result = await cancelReservation(item.id);
							if (result && result.code === 200) {
								// 更新本地预约状态
								const index = reservations.value.findIndex(r => r.id === item.id);
								if (index > -1) {
									reservations.value[index].status = 2; // 设置为已失效
									reservations.value[index].statusText = '已失效';
									// 触发视图更新
									reservations.value = [...reservations.value];
								}
								
								uni.showToast({
									title: '取消成功',
									icon: 'success',
									duration: 2000
								});
							} else {
								uni.showToast({
									title: result.message || '取消失败，请重试',
									icon: 'none',
									duration: 3000
								});
							}
						} catch (error) {
							console.error('取消预约失败:', error);
							uni.showToast({
								title: '网络错误，请稍后重试',
								icon: 'none',
								duration: 3000
							});
						} finally {
							uni.hideLoading();
						}
					}
				}
			});
		};
		
		// 处理删除预约
		const handleDelete = (item) => {
			// 检查预约状态是否为已失效
			if (item.status !== 2) {
				uni.showToast({
					title: '只能删除已失效的预约',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			uni.showModal({
				title: '删除预约',
				content: '确定要删除此预约记录吗？删除后无法恢复。',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '删除中...' });
						try {
							const result = await deleteReservation(item.id);
							if (result && result.code === 200) {
								// 本地删除该记录，避免重新加载整个列表
								const index = reservations.value.findIndex(r => r.id === item.id);
								if (index > -1) {
									reservations.value.splice(index, 1);
									// 触发视图更新
									reservations.value = [...reservations.value];
								}
								
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 2000
								});
							} else {
								uni.showToast({
									title: result.message || '删除失败，请重试',
									icon: 'none',
									duration: 3000
								});
							}
						} catch (error) {
							console.error('删除预约失败:', error);
							uni.showToast({
								title: '网络错误，请稍后重试',
								icon: 'none',
								duration: 3000
							});
						} finally {
							uni.hideLoading();
						}
					}
				}
			});
		};
		
		// 处理评价预约
		const handleReview = (item) => {
			uni.navigateTo({
				url: `/pages/reservation/review?id=${item.id}`
			});
		};
		
		return {
			loading,
			reservations,
			formatDate,
			formatTime,
			formatDateTime,
			formatIdCard,
			getStatusText,
			getStatusClass,
			// 搜索和筛选相关
			searchKeyword,
			statusFilterIndex,
			statusOptions,
			dateFilter,
			hasFilters,
			handleSearch,
			clearSearch,
			onStatusFilterChange,
			onDateFilterChange,
			clearFilters,
			loadReservations,
			getImageUrl,
			// Add new action handlers
			handleEdit,
			handleCancel,
			handleDelete,
			handleReview
		};
	}
};
</script>

<style lang="scss">
.reservation-list-container {
	min-height: 100vh;
	background-color: #f8f9fa;
	padding-bottom: 40rpx;
	
	.page-header {
		padding: 40rpx 30rpx 30rpx;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		
		.title {
			font-size: 34rpx;
			font-weight: 600;
			color: #333;
		}
	}
	
	.search-filter-section {
		background-color: #fff;
		padding: 20rpx 30rpx;
		position: sticky;
		top: 0;
		z-index: 10;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.search-box {
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 36rpx;
			padding: 12rpx 24rpx;
			margin-bottom: 20rpx;
			
			input {
				flex: 1;
				height: 60rpx;
				font-size: 28rpx;
				margin: 0 16rpx;
			}
			
			.clear-icon {
				padding: 6rpx;
				
				&:active {
					opacity: 0.7;
				}
			}
		}
		
		.filter-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.filter-scrollview {
				display: flex;
				overflow-x: auto;
				width: 75%;
				white-space: nowrap;
				scrollbar-width: none; /* Firefox */
				-ms-overflow-style: none; /* IE and Edge */
				
				&::-webkit-scrollbar {
					display: none; /* Chrome, Safari, Opera */
				}
			}
			
			.filter-item {
				display: flex;
				align-items: center;
				font-size: 28rpx;
				color: #666;
				padding: 10rpx 20rpx;
				margin-right: 20rpx;
				background-color: #f5f5f5;
				border-radius: 24rpx;
				transition: all 0.3s;
				
				&.active {
					background-color: rgba(74, 107, 223, 0.1);
					color: #4a6bdf;
					
					.arrow-icon {
						color: #4a6bdf;
					}
				}
				
				text {
					margin-right: 10rpx;
				}
				
				.arrow-icon {
					display: flex;
				}
			}
			
			.reset-filter {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				color: #4a6bdf;
				padding: 8rpx 16rpx;
				background-color: rgba(74, 107, 223, 0.1);
				border-radius: 24rpx;
				transition: all 0.3s;
				
				text {
					margin-left: 6rpx;
				}
				
				&:active {
					opacity: 0.8;
				}
			}
		}
	}
	
	.content-section {
		padding: 20rpx 30rpx;
	}
	
	.loading-box {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
	}
	
	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		
		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 40rpx;
			opacity: 0.8;
		}
		
		.empty-text {
			color: #666;
			font-size: 32rpx;
			font-weight: 500;
			margin-bottom: 12rpx;
		}
		
		.empty-sub-text {
			color: #999;
			font-size: 28rpx;
		}
	}
	
	.list-content {
		.reservation-card {
			background-color: #fff;
			border-radius: 16rpx;
			margin-bottom: 24rpx;
			padding: 30rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
			transition: all 0.3s;
			
			&:active {
				transform: scale(0.99);
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			}
			
			.card-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;
				border-bottom: 1px solid #f0f0f0;
				padding-bottom: 20rpx;
				
				.exhibition-title {
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
				}
				
				.status-tag {
					font-size: 24rpx;
					padding: 6rpx 20rpx;
					border-radius: 24rpx;
					
					&.status-pending {
						background-color: rgba(250, 140, 22, 0.1);
						color: #fa8c16;
					}
					
					&.status-upcoming {
						background-color: rgba(24, 144, 255, 0.1);
						color: #1890ff;
					}
					
					&.status-expired {
						background-color: rgba(153, 153, 153, 0.1);
						color: #999999;
					}
				}
			}
			
			.card-body {
				.info-item {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;
					
					.info-icon {
						display: flex;
						align-items: center;
						justify-content: center;
						width: 40rpx;
						height: 40rpx;
						border-radius: 50%;
						margin-right: 16rpx;
						
						&.date-icon {
							background-color: rgba(74, 107, 223, 0.1);
						}
						
						&.time-icon {
							background-color: rgba(90, 200, 250, 0.1);
						}
						
						&.person-icon {
							background-color: rgba(255, 149, 0, 0.1);
						}
					}
					
					.info-text {
						font-size: 28rpx;
						color: #666;
					}
				}
			}
			
			.card-footer {
				margin-top: 24rpx;
				padding-top: 20rpx;
				border-top: 1px solid #f0f0f0;
				
				.create-time {
					font-size: 24rpx;
					color: #999;
				}
				
				.card-actions {
					margin-top: 24rpx;
					display: flex;
					justify-content: flex-end;
					
					.action-btn {
						height: 64rpx;
						padding: 0 24rpx;
						margin-left: 20rpx;
						font-size: 28rpx;
						border-radius: 32rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						transition: all 0.3s;
						
						/* Reset default button styles */
						background-color: transparent;
						&::after {
							border: none;
						}
						
						&.edit-btn {
							background-color: rgba(24, 144, 255, 0.1);
							color: #1890ff;
							border: 1px solid rgba(24, 144, 255, 0.3);
							
							&:active {
								opacity: 0.8;
							}
						}
						
						&.cancel-btn {
							background-color: rgba(250, 140, 22, 0.1);
							color: #fa8c16;
							border: 1px solid rgba(250, 140, 22, 0.3);
							
							&:active {
								opacity: 0.8;
							}
						}
						
						&.delete-btn {
							background-color: rgba(255, 77, 79, 0.1);
							color: #ff4d4f;
							border: 1px solid rgba(255, 77, 79, 0.3);
							
							&:active {
								opacity: 0.8;
							}
						}
						
						&.review-btn {
							background-color: rgba(82, 196, 26, 0.1);
							color: #52c41a;
							border: 1px solid rgba(82, 196, 26, 0.3);
							
							&:active {
								opacity: 0.8;
							}
						}
					}
				}
			}
		}
	}
}
</style> 